import { jwtDecode } from 'jwt-decode';

const TokenKey = 'bs_admin_token';
const UserKey = 'bs_admin_user';
const RememberMeKey = 'bs_admin_remember';

/**
 * 从localStorage获取token
 */
export function getToken() {
  return localStorage.getItem(TokenKey);
}

/**
 * 保存token到localStorage
 * @param {string} token 
 */
export function setToken(token) {
  return localStorage.setItem(TokenKey, token);
}

/**
 * 从localStorage移除token
 */
export function removeToken() {
  return localStorage.removeItem(TokenKey);
}

/**
 * 保存用户信息到localStorage
 * @param {object} user 
 */
export function setUser(user) {
  return localStorage.setItem(UserKey, JSON.stringify(user));
}

/**
 * 从localStorage获取用户信息
 */
export function getUser() {
  const userStr = localStorage.getItem(UserKey);
  return userStr ? JSON.parse(userStr) : null;
}

/**
 * 从localStorage移除用户信息
 */
export function removeUser() {
  return localStorage.removeItem(UserKey);
}

/**
 * 保存记住我状态
 * @param {boolean} remember 
 */
export function setRememberMe(remember) {
  return localStorage.setItem(RememberMeKey, remember);
}

/**
 * 获取记住我状态
 */
export function getRememberMe() {
  return localStorage.getItem(RememberMeKey) === 'true';
}

/**
 * 检查token是否过期
 * @param {string} token 
 * @returns {boolean}
 */
export function isTokenExpired(token) {
  if (!token) return true;
  
  try {
    const decoded = jwtDecode(token);
    const currentTime = Date.now() / 1000;
    return decoded.exp < currentTime;
  } catch (error) {
    console.error('Token解析失败', error);
    return true;
  }
}

/**
 * 从token中解析用户信息
 * @param {string} token 
 * @returns {object|null}
 */
export function getUserFromToken(token) {
  if (!token) return null;
  
  try {
    return jwtDecode(token);
  } catch (error) {
    console.error('Token解析失败', error);
    return null;
  }
}

/**
 * 检查是否有登录权限
 * @returns {boolean}
 */
export function hasLogin() {
  const token = getToken();
  return token && !isTokenExpired(token);
} 